/**********************************************************************
 * 
 *
 * @url: /services/apexrest/rest
 * @data:
 *  {
        
    }
*************************************************************************/
@RestResource(urlMapping='/CRM/upsertTmsGetDataREST/*')
global without sharing class UpsertTmsGetDataREST {
    @HttpPost
    global static RestReturnMessage doGetData() {
    	String fbRcordId = Utils.getRecordTypeIdByDevNameAndObjName('LogicFeedBack', 'Feedback__c');
    	RestReturnMessage message = null;

    	String ts = null;
    	try {
    	   ts = [select Id , Ts__c from Feedback__c where  RecordTypeId=:fbRcordId  and Ts__c != null order by Ts__c desc limit 1 ].Ts__c.format('yyyy-MM-dd HH:mm:ss');
    	}
    	catch (Exception e) {
    	    ts = '2018-12-01 00:00:00';
    	}
    	String msg = '';
    	///调用接口获取tms的数据 
    	String sql = ' select * from (select  customer_order_no ncid , pri ,dest_customer_namec accountname , notes,company_name carriername , '+
    	' to_char(outbound_time,\'yyyy-MM-dd HH24:mi:ss\')  sendtime  , bilno ,'+
    	' to_char(edittime,\'yyyy-MM-dd HH24:mi:ss\')  ts  , cancel_flag cflag from idx_so_sf_MK where dest_customerno != \'NULL\' ' + 
        '  and SUBSTR(customer_order_no, 0, 2)=\'XC\' ';
    	sql +=  ' and to_char(edittime,\'yyyy-MM-dd HH24:mi:ss\') >= \''+ts+'\'   order by ts ) where rownum <= 2000  ';
    	String postURL = Label.queryTmsURL;
        System.debug(sql);
        String timestamp = String.valueOf(System.now().getTime());
        String data = EncodingUtil.base64Encode(Blob.valueOf(sql));

        String sign = EncodingUtil.convertToHex(Crypto.generateDigest('MD5',Blob.valueOf(timestamp+data  + timestamp)));
        ///发送请求
        //生成POST请求
        System.debug(data);
        System.debug(timestamp);
         System.debug(sign);
        HttpRequest req = new HttpRequest(); 
        req.setBody('data=' + EncodingUtil.urlEncode(data,'UTF-8')+'&timestamp='+timestamp+'&sign='+sign);
        req.setEndpoint(postURL); 
        req.setMethod('POST');
        HttpResponse res = Utils.postRequest(req,1); 
        //System.debug(res.getBody());

        if (res.getStatusCode() == 200) {


             Map<String,Object> r =null;
                 //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{"code":"1","msg":"success","data":[{"pri":3,"carriername":"成都通驰物流有限公司","accountname":"四川绵阳四0四医院","ts":"2018-11-26 13:21:13","ncid":"XC02181137456","bilno":"1072889","sendtime":"2018-11-26 13:21:13","notes":"附批件报告","cflag":"N"}]}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }

             if(r.get('code') == 0|| r.get('code')=='0' ){
             		Map<String, Object> res1 = (Map<String, Object> ) JSON.deserializeUntyped(((String)r.get('result')));
             		Map<String ,LogicBean>  lgMap  = new Map<String,LogicBean>();
             		Set<String> deleSet = new Set<String>();
             		if(String.valueOf(res1.get('code')) == '1'){
             			List<Object> resList = (List<Object> ) res1.get('data');
                        System.debug('获取的数据条数:'+ resList.size() );
             			for(Object o :resList){

             				Map<String,Object> mo = (Map<String,Object>) o;
             				LogicBean lgb =  new LogicBean(mo);
             				if(lgb.cflag == 'Y'){
             					deleSet.add(lgb.ncid);
             				}else{
             					lgMap.put(lgb.ncid,lgb);
             					
             				}
             				

             			}

             			message = doSaveRes(lgMap,deleSet,fbRcordId );

             		}else{
             			msg = String.valueOf(res1.get('msg'));
             			message = Utils.getRestReturnMessage(false,msg+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());

             		}

             }else{
             	msg = String.valueOf(r.get('msg'));
         		message = Utils.getRestReturnMessage(false,msg+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());
             }
         }else{
         	msg = '网络错误!'+ res.getBody();
         	message = Utils.getRestReturnMessage(false,msg+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());


         }



        return message ;
    }

    global static RestReturnMessage doSaveRes(Map<String,LogicBean> lgMap ,Set<String> cancels,String fbRcordId){

    	   RestReturnMessage message = null;

           System.debug(lgMap.keySet().size());
    	Map<String,Feedback__c> exitlgMap = new Map<String,Feedback__c>();
    	///找出已经存在的
    	for(Feedback__c fb :[select Id ,ExwareNo__c from Feedback__c where RecordTypeId =:fbRcordId and  ExwareNo__c in:lgMap.keySet() ]){
    		exitlgMap.put(fb.ExwareNo__c,fb);
    	}
    	List<Feedback__c> upsertList = new List<Feedback__c>();
    	for(String k :lgMap.keySet()){
    		LogicBean lgb = lgMap.get(k);
    		Feedback__c fb = new Feedback__c();
    		if(exitlgMap.containsKey(k)){
    			fb.Id = exitlgMap.get(k).Id;
    		}
    		fb.ExwareNo__c = k;
    		fb.Name = 'WL-'+lgb.ncid;
    		fb.CarrierType__c = lgb.pri ;

    		fb.RecordTypeId = fbRcordId;
	    	fb.ERPComment__c = lgb.notes;
	    	fb.CarriageNumber__c = lgb.bilno;  
	    	fb.LogisCompany__c = lgb.carriername;

    		fb.Client__c = lgb.accountname;
    		fb.Ts__c = DateTime.valueOf(lgb.ts);
    		try{
		        fb.Sendtime__c = DateTime.valueOf(lgb.sendtime);
		    }catch(Exception e){
		        fb.Sendtime__c = null;
		     }
    		upsertList.add(fb);
    		if(cancels.contains(k))cancels.remove(k);
    	}
    	///找出要删除的
    	List<Feedback__c> deList = new List<Feedback__c>();
    	if(cancels.size() > 0){
    		deList = [select Id  from Feedback__c where RecordTypeId =:fbRcordId and  ExwareNo__c in:cancels ];
    	}
    	Savepoint sp = Database.setSavepoint();
    	try {
            System.debug('保存的数据条数:'+ upsertList.size() );
    	    if(deList.size() > 0)delete deList;
            System.debug('删除的数据条数:'+ deList.size() );
    	    if(upsertList.size() > 0) upsert upsertList;
    	    message = Utils.getRestReturnMessage(false,'保存成功!',new List<Map<String ,String>>());

    	}catch (Exception e) {
    	    Database.rollback(sp);
    	    message = Utils.getRestReturnMessage(false,e.getMessage() + ' - ' + e.getStackTraceString()+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());

    	}
    	


    	return message;
    }
    global class LogicBean{
        public String ncid ;
        public String pri ;
        public String accountname;
        public String cflag;
        public String  sendtime;
        public String ts ;
        public String notes ;
        public String carriername ; 
        public String bilno;   
        public LogicBean(Map<String ,Object> o){
          ncid = getStringValue(o.get('ncid'));
          pri = getStringValue(o.get('pri'));
          bilno = getStringValue(o.get('bilno'));

          accountname = getStringValue(o.get('accountname'));
          cflag = getStringValue(o.get('cflag'));

          sendtime = getStringValue(o.get('sendtime'));
          ts = getStringValue(o.get('ts'));

          notes = getStringValue(o.get('notes'));
          carriername = getStringValue(o.get('carriername'));

        }
        public String getStringValue(Object o ){
        	if(o == null) return null ;
        	return String.valueOf(o).trim();
        }
    }
}